package com.oocl.euc.authentication.tool;

import com.oocl.euc.framework.authentication.common.JwtToken;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class CookieHelper {
    public Cookie getCookie(HttpServletRequest httpRequest, String cookieName) {
        Cookie[] cookies = httpRequest.getCookies();
        if(null == cookies){
            return null;
        }
        for(Cookie cookie : cookies) {
            if(cookieName.equalsIgnoreCase(cookie.getName())){
                return cookie;
            }
        }
        return null;
    }

    public void refreshTokenCookieForOOCL(HttpServletResponse response, Cookie jwtTokenCookie, JwtToken accessToken){
        if(null == jwtTokenCookie) {
            return;
        }
        jwtTokenCookie.setValue(accessToken.getRawToken());
        jwtTokenCookie.setDomain(".oocl.com");
        jwtTokenCookie.setPath("/");
        response.addCookie(jwtTokenCookie);
    }

    public void addOrRefreshTokenCookieForOOCL(HttpServletResponse response, Cookie jwtTokenCookie, String cookieName, JwtToken accessToken){
        if(null == jwtTokenCookie) {
            jwtTokenCookie = new Cookie(cookieName, accessToken.getRawToken());
        } else {
            jwtTokenCookie.setValue(accessToken.getRawToken());
        }
        jwtTokenCookie.setValue(accessToken.getRawToken());
        jwtTokenCookie.setDomain(".oocl.com");
        jwtTokenCookie.setPath("/");
        response.addCookie(jwtTokenCookie);
    }
}
